package java_thinking.unit_21._21_7;

import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Desc:   7-20 使用私有的 Executor，并且该 Executor 的生命周期受限于方法调用；
 *          1.CheckForMail能在多台主机上并行的姜茶新邮件，它创建一个私有的 Executor ，并向
 *            每台主机提交一个任务，然后，当所有邮件检查任务都完成后，关闭 Executor 并等待结束
 * @author: cww
 * @DateTime: 2019-06-16 17:04
 */

public class CheckForMail {
    public boolean checkMail(Set<String> hosts, long timeout, TimeUnit unit) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        //这里之所以不用 volatile 因为能从Runnable内部访问 hasNewMail，因此要避免被修改指向新对象，故要用final
        final AtomicBoolean hasNewMail = new AtomicBoolean(false);
        try {
            for (final String host : hosts) {
                exec.execute(new Runnable() {
                    @Override
                    public void run() {
                        if (checkMail(host)) {
                            hasNewMail.set(true);
                        }
                    }
                });
            }
        } finally {
            exec.shutdown();
            exec.awaitTermination(timeout, unit);
        }
        return hasNewMail.get();
    }
    private boolean checkMail(String host) {
        // Check for mail
        return false;
    }
}
